'use strict';

const moment = require('moment');

const Service = require('egg').Service;

class CommonService extends Service {

  paging(payload = {}) {
    const { offset = 0, limit = 0, from = 1, size = 10, sorter, endAt, updatedAt, createdAt } = this.ctx.request.query;

    payload.where instanceof Object || Object.assign(payload, { where: {} });
    endAt && Object.assign(payload.where, { endAt: { '$between': [moment(isNaN(endAt) ? endAt : Number(endAt)).format('YYYY-MM-DD'), moment(isNaN(endAt) ? endAt : Number(endAt)).add(1, 'days').format('YYYY-MM-DD')] } });
    updatedAt && Object.assign(payload.where, { updatedAt: { '$between': [moment(isNaN(updatedAt) ? updatedAt : Number(updatedAt)).format('YYYY-MM-DD'), moment(isNaN(updatedAt) ? updatedAt : Number(updatedAt)).add(1, 'days').format('YYYY-MM-DD')] } });
    createdAt && Object.assign(payload.where, { createdAt: { '$between': [moment(isNaN(createdAt) ? createdAt : Number(createdAt)).format('YYYY-MM-DD'), moment(isNaN(createdAt) ? createdAt : Number(createdAt)).add(1, 'days').format('YYYY-MM-DD')] } });

    Array.isArray(payload.order) || Object.assign(payload, { order: [] });
    if (sorter) {
      const start = sorter.indexOf('_');
      const end = sorter.indexOf('end');
      const key = sorter.substr(0, start);
      const value = sorter.substring(start + 1, end).toLocaleUpperCase();
      payload.order.push([key, value]);
    } else {
      payload.order.push(['id', 'DESC']);
    }

    if (from || size) {
      Object.assign(payload, { offset: size * (from - 1), limit: Number(size) });
    } else {
      Object.assign(payload, offset && limit ? { offset, limit } : limit ? { limit } : offset ? { offset } : {});
    }

    return payload;
  }

}

module.exports = CommonService;